package com.example.authority.controller;
import com.alibaba.excel.EasyExcel;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;


import com.example.authority.service.UserService;
import com.example.authority.entity.User ;
import com.example.authority.service.SeekService;
import com.example.authority.entity.Seek ;
import com.example.authority.service.DownloadlogService;
import com.example.authority.entity.Downloadlog;



/**
 * @program:   
 * @ClassName:DownloadlogController
 * @description: DownloadlogController前端控制器
 *       
 * @Version 3.0
 **/
@Tag(name = "下载记录 前端控制器")
    @RestController
@RequestMapping("/downloadlog")
    public class DownloadlogController {

@Resource
private DownloadlogService downloadlogService;
@Resource
private UserService userService;
@Resource
private SeekService seekService;

/**
 * 新增
 * @param downloadlog
 * @return
 */
@Operation(summary = "新增")
@PostMapping
public Result save(@RequestBody Downloadlog downloadlog){
        return Result.success(downloadlogService.save(downloadlog));
        }
/**
* 修改
*
* @param downloadlog
* @return
*/
@Operation(summary = "修改")
@PutMapping("/{id}")
public Result update(@PathVariable Long id,@RequestBody Downloadlog downloadlog) {
        return Result.success(downloadlogService.updateById(downloadlog));
        }

/**
 * 查询所有Downloadlog
 * @return
 */
@Operation(summary = "查询所有Downloadlog")
@GetMapping
public Result findAll(){
        return Result.success(downloadlogService.list());
        }
/**
  * 获取单个
  * @param id
  * @return
  */
@Operation(summary = "获取单个")
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id){
        return Result.success(downloadlogService.getById(id));
        }
/**
 * 分页显示
 * @param
 * @param pageNum
 * @param pageSize
 * @return
 */
@Operation(summary = "分页显示")
@GetMapping("/page")
public Result findPage(
@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(required = false) Long userId) {

        LambdaQueryWrapper<Downloadlog> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果提供了userId，添加查询条件
        if (userId != null) {
            queryWrapper.eq(Downloadlog::getUid, userId);
        }

        queryWrapper.orderByDesc(Downloadlog::getId);
        Page<Downloadlog> page = downloadlogService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Downloadlog> records = page.getRecords();
        for (Downloadlog downloadlog : records) {
            User user = userService.getById(downloadlog.getUid());
            if (ObjectUtil.isNotEmpty(user)) {
                downloadlog.setUser(user);
            }
            Seek seek = seekService.getById(downloadlog.getSid());
            if (ObjectUtil.isNotEmpty(seek)) {
                downloadlog.setSeek(seek);
            }
        }
        page.setRecords(records);
        return Result.success(page);
}
/**
* 单个删除
* @param id
* @return
*/
@Operation(summary = "单个删除")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
        return Result.success(downloadlogService.removeById(id));
        }
/**
* 批量删除
* @param ids
* @return
*/
@Operation(summary = "批量删除")
@DeleteMapping("/batch/{ids}")
@Transactional
public Result deleteByIds(@PathVariable String[]ids){
        return Result.success(downloadlogService.removeByIds(Arrays.asList(ids)));
        }

/**
 * 批量导出
 * 使用的技术为alibaba下面的easyexcel
 * 写数据
 *
 * @param ids
 * @return
 */
@Operation(summary = "批量导出")
@GetMapping("/batch/export/{ids}")
public void exportByIds(@PathVariable String[] ids, HttpServletResponse response) throws IOException {

        List<Downloadlog> list = downloadlogService.listByIds(Arrays.asList(ids));
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("downloadlog导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Downloadlog.class).sheet("sheel1").doWrite(list);

        }

/**
 * 批量导入
 * 使用的技术为alibaba下面的easyexcel
 * 读数据
 *
 * @param
 */
@Operation(summary = "批量导入")
@PostMapping("/batch/upload")
public Result writeExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Downloadlog.class, new PageReadListener<Downloadlog>(dataList -> {
        dataList.forEach(entity -> downloadlogService.save(entity.toBuilder().id(null).build()));
        })).sheet().doRead();
        return Result.success();
        }

/**
 * 检查用户是否满足下载等级要求
 * @param uid 用户ID
 * @param sid 种子ID
 * @return 是否满足下载要求
 */
@Operation(summary = "检查下载等级要求")
@GetMapping("/checkDownloadGrade")
public Result checkDownloadGrade(@RequestParam Long uid, @RequestParam Long sid) {
    // 获取用户信息
    User user = userService.getById(uid);
    if (user == null) {
        return Result.error("用户不存在");
    }

    // 获取种子信息
    Seek seek = seekService.getById(sid);
    if (seek == null) {
        return Result.error("种子不存在");
    }

    // 检查用户等级是否满足要求
    if (user.getGrade() >= seek.getDownloadGrade()) {
        // 创建下载记录
        Downloadlog downloadlog = Downloadlog.builder()
                .uid(uid)
                .sid(sid)
                .build();
        downloadlogService.save(downloadlog);

        // 更新用户的下载次数
        User uploader = userService.getById(seek.getUserid());
        if (uploader != null) {
            uploader.setDownloadNum(uploader.getDownloadNum() + 1);
            userService.updateById(uploader);
        }

        // 更新种子的下载次数
        seek.setDownloadnum(seek.getDownloadnum() + 1);
        seekService.updateById(seek);

        return Result.success(true);
    }

    return Result.success(false);
}

        }